package top.kaoshanji.p2ch19a;

import top.kaoshanji.p2ch19a.support.ConcurrentLimitException;

import java.util.concurrent.Semaphore;

/**
 * 代码清单-p2ch19a-530页a：Semaphore应用示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/27 19:08
 */
public class AccessControlService {

    private static final int MAX_PERMITS = 100;
    private Semaphore permits = new Semaphore(MAX_PERMITS, true);

    public boolean login(String name, String password) {
        if (!permits.tryAcquire()) {
            // 同时登录用户数超过限制
            throw new ConcurrentLimitException();
        }

        // ..其他验证
        return true;
    }

    public void logout(String name) {
        permits.release();
    }

}
